package cn.com.dhcc.turbo.service.sysmgr;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.turbo.entity.sysmgr.taskmont.QuartzTriggerVO;
import cn.com.dhcc.turbo.entity.sysmgr.taskmont.TriggerRowWapper;

/**
 * 定时任务监控service
 * @author Macky_He
 * @version [数据交换平台V1.2.1]
 */
@Service
public class TaskMonitorService extends BaseService {
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.SYS);

	/**
	 * <b>获取定时任务列表</b>
	 * 
	 * @param jobName
	 *            任务名称
	 * @param status
	 *            任务状态
	 * @return {@link QuartzTriggerVO}
	 */
	public PagerData<QuartzTriggerVO> getJobList(String jobName, String status,
			Pager pager) {
		logger.info("进入方法getJobList");
		StringBuilder sb = new StringBuilder(
				"SELECT t.TRIGGER_NAME triggerName, t1.CRON_EXPRESSION cronExpression, t.JOB_NAME jobName, t.PREV_FIRE_TIME prevTime, t.NEXT_FIRE_TIME nexTime, t.TRIGGER_STATE state, t.START_TIME startTime ");
		sb.append(" FROM " + SI_TABLE("TURBO_QRTZ_TRIGGERS") + " t left join "
				+ SI_TABLE("TURBO_QRTZ_CRON_TRIGGERS") + " t1 ");
		sb.append(" ON t1.TRIGGER_NAME = t.TRIGGER_NAME ");
		sb.append(" WHERE 1 = 1 ");
		if (!StringUtils.isEmpty(jobName)) {
			sb.append("AND t.JOB_NAME LIKE '%");
			sb.append(jobName);
			sb.append("%'");
		}
		if (!StringUtils.isEmpty(status)) {
			sb.append("AND t.TRIGGER_STATE LIKE '%");
			sb.append(status.toUpperCase());
			sb.append("%'");
		}
		sb.append(" ORDER BY t.TRIGGER_STATE ");
		PagerData<QuartzTriggerVO> vo = null;
		try {
			vo = CM.getDao().getPagerList("查询任务列表", sb.toString(), pager,
					new TriggerRowWapper(), new Object[] {});
		} catch (DaoException e) {
			logger.error("查询Quartz任务列表发生异常:" + e.getMessage());
		}
		logger.info("执行完毕getJobList");
		return vo;
	}
}
